<template>
  <el-card class="content-card" shadow="hover">
    <template #header>
      <div class="card-header">
        <span>API文档 - 进阶示例</span>
      </div>
    </template>

    <div class="content-container">
      <div class="api-content">
        <div class="section" id="intro">
          <div class="section-header"><h2>进阶示例介绍</h2></div>
          <p class="intro-text">
            本页面提供了API的进阶使用示例，适合已经熟悉基础API操作的开发者。
            这些示例展示了更复杂的场景和高级功能，帮助您充分利用我们API的全部潜力。
          </p>
        </div>

        <div class="section" id="batch-operations">
          <div class="section-header"><h2>批量操作</h2></div>
          <p>以下示例展示了如何高效地执行批量数据操作：</p>
          <div class="code-block">
            <div class="code-header">
              <span>JavaScript</span>
              <el-button
                type="primary"
                size="small"
                :icon="CopyDocument"
                @click="copyCode(batchCode)"
                class="copy-btn"
              >
                复制代码
              </el-button>
            </div>
            <MonacoEditor
              style="height: 220px; border-radius: 6px; overflow: hidden"
              v-model="batchCode"
              language="javascript"
              :options="{
                readOnly: true,
                minimap: { enabled: false },
                height: '220px',
              }"
            />
          </div>
        </div>

        <div class="section" id="real-time-data">
          <div class="section-header"><h2>实时数据处理</h2></div>
          <p>通过WebSocket实现实时数据更新和处理：</p>
          <div class="code-block">
            <div class="code-header">
              <span>JavaScript</span>
              <el-button
                type="primary"
                size="small"
                :icon="CopyDocument"
                @click="copyCode(realtimeCode)"
                class="copy-btn"
              >
                复制代码
              </el-button>
            </div>
            <MonacoEditor
              style="height: 220px; border-radius: 6px; overflow: hidden"
              v-model="realtimeCode"
              language="javascript"
              :options="{
                readOnly: true,
                minimap: { enabled: false },
                height: '220px',
              }"
            />
          </div>
        </div>

        <div class="section" id="advanced-filtering">
          <div class="section-header"><h2>高级筛选和排序</h2></div>
          <p>使用复杂查询参数进行高级数据筛选和排序：</p>
          <div class="code-block">
            <div class="code-header">
              <span>JavaScript</span>
              <el-button
                type="primary"
                size="small"
                :icon="CopyDocument"
                @click="copyCode(filteringCode)"
                class="copy-btn"
              >
                复制代码
              </el-button>
            </div>
            <MonacoEditor
              style="height: 220px; border-radius: 6px; overflow: hidden"
              v-model="filteringCode"
              language="javascript"
              :options="{
                readOnly: true,
                minimap: { enabled: false },
                height: '220px',
              }"
            />
          </div>
        </div>

        <div class="section" id="caching">
          <div class="section-header"><h2>缓存策略</h2></div>
          <p>实现高效的API缓存策略，减少请求次数并提高性能：</p>
          <div class="code-block">
            <div class="code-header">
              <span>JavaScript</span>
              <el-button
                type="primary"
                size="small"
                :icon="CopyDocument"
                @click="copyCode(cachingCode)"
                class="copy-btn"
              >
                复制代码
              </el-button>
            </div>
            <MonacoEditor
              style="height: 220px; border-radius: 6px; overflow: hidden"
              v-model="cachingCode"
              language="javascript"
              :options="{
                readOnly: true,
                minimap: { enabled: false },
                height: '220px',
              }"
            />
          </div>
        </div>

        <div class="section" id="rate-limiting">
          <div class="section-header"><h2>速率限制处理</h2></div>
          <p>优雅地处理API速率限制，实现请求重试和节流：</p>
          <div class="code-block">
            <div class="code-header">
              <span>JavaScript</span>
              <el-button
                type="primary"
                size="small"
                :icon="CopyDocument"
                @click="copyCode(rateLimitCode)"
                class="copy-btn"
              >
                复制代码
              </el-button>
            </div>
            <MonacoEditor
              style="height: 220px; border-radius: 6px; overflow: hidden"
              v-model="rateLimitCode"
              language="javascript"
              :options="{
                readOnly: true,
                minimap: { enabled: false },
                height: '220px',
              }"
            />
          </div>
        </div>
      </div>

      <!-- 右侧悬浮目录 -->
      <div class="toc">
        <div class="toc-title">目录</div>
        <div class="toc-item" @click="scrollToSection('intro')">
          进阶示例介绍
        </div>
        <div class="toc-item" @click="scrollToSection('batch-operations')">
          批量操作
        </div>
        <div class="toc-item" @click="scrollToSection('real-time-data')">
          实时数据处理
        </div>
        <div class="toc-item" @click="scrollToSection('advanced-filtering')">
          高级筛选和排序
        </div>
        <div class="toc-item" @click="scrollToSection('caching')">
          缓存策略
        </div>
        <div class="toc-item" @click="scrollToSection('rate-limiting')">
          速率限制处理
        </div>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { ref } from 'vue';
import { CopyDocument } from '@element-plus/icons-vue';
import MonacoEditor from '@/components/MonacoEditor.vue';

// 示例代码
const batchCode = ref(`// 批量创建数据
async function batchCreate(items) {
  try {
    // 准备批量创建的数据
    const payload = {
      items: items.map(item => ({
        title: item.title,
        content: item.content,
        tags: item.tags || [],
        isPublic: item.isPublic || false
      }))
    };
    
    // 调用批量创建API
    const response = await apiClient.data.batchCreate(payload);
    console.log('批量创建成功:', response.data);
    
    // 处理部分成功的情况
    if (response.data.partialSuccess) {
      console.warn('部分项目创建失败:', response.data.failedItems);
    }
    
    return response.data.successItems;
  } catch (error) {
    console.error('批量创建失败:', error);
    throw error;
  }
}`);

const realtimeCode = ref(`// 初始化WebSocket连接
function initializeRealTimeUpdates(dataId) {
  // 创建WebSocket连接
  const wsUrl = \`wss://api.example.com/ws?apiKey=\${apiClient.getApiKey()}&dataId=\${dataId}\`;
  const socket = new WebSocket(wsUrl);
  
  // 连接建立时的处理
  socket.onopen = () => {
    console.log('WebSocket连接已建立');
    // 订阅特定数据的更新
    socket.send(JSON.stringify({
      action: 'subscribe',
      channel: \`data.\${dataId}.updates\`
    }));
  };
  
  // 接收消息的处理
  socket.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);
      console.log('收到实时更新:', data);
      
      // 根据消息类型处理不同的更新
      switch (data.type) {
        case 'update':
          handleDataUpdate(data.payload);
          break;
        case 'delete':
          handleDataDelete(data.payload);
          break;
        case 'status':
          handleStatusChange(data.payload);
          break;
      }
    } catch (error) {
      console.error('处理WebSocket消息失败:', error);
    }
  };
  
  // 错误处理
  socket.onerror = (error) => {
    console.error('WebSocket错误:', error);
  };
  
  // 连接关闭的处理
  socket.onclose = (event) => {
    console.log(\`WebSocket连接已关闭: 代码 \${event.code}, 原因: \${event.reason}\`);
    // 尝试重新连接
    setTimeout(() => initializeRealTimeUpdates(dataId), 5000);
  };
  
  return socket;
}`);

const filteringCode = ref(`// 高级筛选和排序
async function advancedSearch(options) {
  try {
    // 构建高级查询参数
    const queryParams = {
      // 基础分页参数
      page: options.page || 1,
      pageSize: options.pageSize || 20,
      
      // 排序参数
      sortBy: options.sortBy || 'createdAt',
      sortOrder: options.sortOrder || 'desc',
      
      // 高级筛选条件
      filters: {
        // 日期范围筛选
        dateRange: options.dateRange ? {
          field: options.dateRange.field || 'createdAt',
          start: options.dateRange.start,
          end: options.dateRange.end
        } : null,
        
        // 标签筛选
        tags: options.tags || [],
        
        // 全文搜索
        searchText: options.searchText || '',
        searchFields: options.searchFields || ['title', 'content'],
        
        // 数值范围筛选
        numericFilters: options.numericFilters || [],
        
        // 状态筛选
        status: options.status || null,
        
        // 关联数据筛选
        relations: options.relations || {}
      },
      
      // 指定返回字段
      fields: options.fields || null
    };
    
    // 移除空值
    Object.keys(queryParams.filters).forEach(key => {
      if (queryParams.filters[key] === null || 
          (Array.isArray(queryParams.filters[key]) && queryParams.filters[key].length === 0) ||
          (typeof queryParams.filters[key] === 'object' && Object.keys(queryParams.filters[key]).length === 0)) {
        delete queryParams.filters[key];
      }
    });
    
    // 调用高级搜索API
    const response = await apiClient.data.advancedSearch(queryParams);
    console.log('高级搜索结果:', response.data);
    return response.data;
  } catch (error) {
    console.error('高级搜索失败:', error);
    throw error;
  }
}`);

const cachingCode = ref(`// 创建缓存管理器
class ApiCacheManager {
  constructor(options = {}) {
    this.cache = new Map();
    this.defaultTTL = options.defaultTTL || 5 * 60 * 1000; // 默认5分钟
    this.maxSize = options.maxSize || 100; // 最大缓存条目数
  }
  
  // 生成缓存键
  generateCacheKey(endpoint, params) {
    return \`\${endpoint}::\${JSON.stringify(params)}\`;
  }
  
  // 获取缓存数据
  get(endpoint, params) {
    const key = this.generateCacheKey(endpoint, params);
    const cachedItem = this.cache.get(key);
    
    if (!cachedItem) return null;
    
    // 检查是否过期
    if (Date.now() > cachedItem.expiry) {
      this.cache.delete(key);
      return null;
    }
    
    console.log(\`缓存命中: \${endpoint}\`);
    return cachedItem.data;
  }
  
  // 设置缓存数据
  set(endpoint, params, data, ttl = this.defaultTTL) {
    // 如果缓存已满，删除最早的条目
    if (this.cache.size >= this.maxSize) {
      const oldestKey = this.cache.keys().next().value;
      this.cache.delete(oldestKey);
    }
    
    const key = this.generateCacheKey(endpoint, params);
    this.cache.set(key, {
      data,
      expiry: Date.now() + ttl,
      createdAt: Date.now()
    });
    
    console.log(\`缓存设置: \${endpoint}, TTL: \${ttl}ms\`);
  }
  
  // 清除特定缓存
  invalidate(endpoint, params = null) {
    if (params) {
      // 清除特定参数的缓存
      const key = this.generateCacheKey(endpoint, params);
      this.cache.delete(key);
    } else {
      // 清除特定端点的所有缓存
      const prefix = \`\${endpoint}::\`;
      for (const key of this.cache.keys()) {
        if (key.startsWith(prefix)) {
          this.cache.delete(key);
        }
      }
    }
    
    console.log(\`缓存已清除: \${endpoint}\`);
  }
  
  // 清除所有缓存
  clear() {
    this.cache.clear();
    console.log('所有缓存已清除');
  }
}`);

const rateLimitCode = ref(`// 速率限制处理器
class RateLimitHandler {
  constructor(options = {}) {
    this.maxRetries = options.maxRetries || 3;
    this.retryDelay = options.retryDelay || 1000;
    this.retryMultiplier = options.retryMultiplier || 2;
    this.requestsPerMinute = options.requestsPerMinute || 60;
    
    this.requestTimestamps = [];
    this.pendingRequests = [];
  }
  
  // 检查是否可以发送请求
  canMakeRequest() {
    const now = Date.now();
    // 清理一分钟前的请求记录
    this.requestTimestamps = this.requestTimestamps.filter(
      timestamp => now - timestamp < 60000
    );
    
    return this.requestTimestamps.length < this.requestsPerMinute;
  }
  
  // 记录请求
  recordRequest() {
    this.requestTimestamps.push(Date.now());
  }
  
  // 处理请求队列
  processQueue() {
    if (this.pendingRequests.length === 0) return;
    
    if (this.canMakeRequest()) {
      const nextRequest = this.pendingRequests.shift();
      this.recordRequest();
      nextRequest.execute();
    }
    
    // 继续处理队列
    if (this.pendingRequests.length > 0) {
      setTimeout(() => this.processQueue(), 100);
    }
  }
  
  // 执行请求，处理速率限制
  async executeRequest(requestFn, ...args) {
    let retries = 0;
    let delay = this.retryDelay;
    
    const execute = async () => {
      try {
        return await requestFn(...args);
      } catch (error) {
        // 检查是否是速率限制错误
        if (error.response && error.response.status === 429) {
          if (retries < this.maxRetries) {
            retries++;
            console.log(\`遇到速率限制，第\${retries}次重试，等待\${delay}ms...\`);
            
            // 等待指定时间后重试
            await new Promise(resolve => setTimeout(resolve, delay));
            
            // 指数退避策略
            delay *= this.retryMultiplier;
            
            // 重试请求
            return execute();
          } else {
            console.error('达到最大重试次数，请求失败');
            throw error;
          }
        } else {
          // 非速率限制错误，直接抛出
          throw error;
        }
      }
    };
    
    // 如果可以立即发送请求
    if (this.canMakeRequest()) {
      this.recordRequest();
      return execute();
    } else {
      // 否则加入队列
      return new Promise((resolve, reject) => {
        this.pendingRequests.push({
          execute: async () => {
            try {
              const result = await execute();
              resolve(result);
            } catch (error) {
              reject(error);
            }
          }
        });
        
        // 开始处理队列
        this.processQueue();
      });
    }
  }
}`);

// 复制代码功能
const copyCode = (code) => {
  navigator.clipboard.writeText(code.value)
    .then(() => {
      ElMessage.success('代码已复制到剪贴板');
    })
    .catch(() => {
      ElMessage.error('复制失败');
    });
};

// 滚动到指定区域
const scrollToSection = (sectionId) => {
  const element = document.getElementById(sectionId);
  if (element) {
    element.scrollIntoView({ behavior: "smooth" });
  }
};
</script>

<style scoped>
.content-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  border-radius: 12px;
  overflow: hidden;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.card-header {
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

:deep(.el-card__body) {
  padding: 0;
  height: calc(100% - 60px);
  overflow-y: auto;
  background: #ffffff;
}

.content-container {
  min-height: 100%;
  padding: 30px;
  padding-right: 280px;
  background: linear-gradient(to bottom, #ffffff 0%, #f8f9fa 100%);
}

.api-content {
  max-width: 1000px;
  margin: 0 auto;
  line-height: 1.8;
  color: #4a5568;
}

.section {
  margin-bottom: 40px;
  padding: 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section h2 {
  margin: 0;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
  position: relative;
  flex: 1;
}

.section h2::before {
  content: "";
  position: absolute;
  left: 0;
  bottom: -2px;
  width: 50px;
  height: 2px;
  background: #409eff;
  border-radius: 1px;
}

.intro-text {
  font-size: 16px;
  line-height: 1.8;
  color: #4a5568;
  margin-bottom: 20px;
}

.code-block {
  margin: 15px 0;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  overflow: hidden;
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
}

.copy-btn {
  margin-left: 10px;
}

/* 右侧悬浮目录样式 */
.toc {
  position: fixed;
  right: 50px;
  top: 50%;
  transform: translateY(-50%);
  background: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  border: 1px solid #e4e7ed;
  min-width: 200px;
}

.toc-title {
  font-weight: 700;
  margin-bottom: 15px;
  color: #2d3748;
  font-size: 18px;
  text-align: center;
  padding-bottom: 10px;
  border-bottom: 2px solid #e2e8f0;
}

.toc-item {
  padding: 12px 16px;
  cursor: pointer;
  color: #4a5568;
  transition: all 0.3s ease;
  border-radius: 8px;
  font-size: 14px;
  margin-bottom: 4px;
  border-left: 3px solid transparent;
  position: relative;
}

.toc-item:hover {
  color: #409eff;
  background: #ecf5ff;
  border-left-color: #409eff;
  transform: translateX(4px);
}

.toc-item:active {
  transform: translateX(2px);
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .content-container {
    padding-right: 30px;
  }

  .toc {
    display: none;
  }
}

@media (max-width: 768px) {
  .content-container {
    padding: 20px 15px;
  }

  .section {
    padding: 20px 15px;
    margin-bottom: 25px;
  }

  .section h2 {
    font-size: 18px;
  }

  .card-header {
    font-size: 16px;
    padding: 15px;
  }
}

/* 滚动条样式 */
:deep(.el-card__body)::-webkit-scrollbar {
  width: 6px;
}

:deep(.el-card__body)::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

:deep(.el-card__body)::-webkit-scrollbar-thumb {
  background: #409eff;
  border-radius: 3px;
}

:deep(.el-card__body)::-webkit-scrollbar-thumb:hover {
  background: #337ecc;
}
</style>